<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
abstract class Base extends CI_Model{

  var $_table;
  var $_columns;

  /* Dont forget to create table columns as properties of the class.
   * */

  function __construct()
  {
    parent::__construct();
    $this->_columns    = $this->discover_table_columns();
    $this->_class_name = strtolower(get_class($this));
    $this->_table      = $this->_class_name.'s';
  }

  function get($id=null){
    $query  = $this->db->get($this->_table, $id);
    $result = $query->result();
    if(count($result) == 1){
     $this->load_array_to_properties(array_shift($result));
     return $this;
    }
    else
      return $result;
  }

  function insert(){
    $this->db->insert($this->_table, $this->discover_table_values());
	}

  function update(){
    $this->db->update($this->_table, $this->discover_table_values());
  }

  function delete(){
    $this->db->where('id', $this->id);
    $this->db->delete($this->_table);
  }

  /* Description: just return an array of strings (column names)
   * Sample     : return array('id', 'name', 'description');
   * */
  abstract protected function discover_table_columns();
  protected function discover_table_values(){
    $result = array();
    foreach($this->_columns as $k=>$v)
      $result[$v] = $this->$v;

    return $result;
  }

  protected function load_array_to_properties($data){

    foreach($data as $k=>$v)
      $this->$k = $v;

  }
}
?>
